﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NHibernate;
using VegetableStore.Providers;
using VegetableStore.Domains;
using System.Web.Script.Serialization;
using NHibernate.Transform;
using VegetableStore.Dto;

namespace VegetableStore.Controllers
{
    [AllowAnonymous]
    public class StoreController : Controller
    {
        private ISession nhibernateSession;

        public StoreController()
        {
            nhibernateSession = SessionProvider.Instance.GetSession();
        }

        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult GetAddressSido()
        {
            try
            {
                IList<AddressDto> sidoList = nhibernateSession.CreateSQLQuery("select distinct sido from Address")
                    .SetResultTransformer(new AliasToBeanResultTransformer(typeof(AddressDto)))
                    .List<AddressDto>();

                return Json(new { result = "SUCCESS", data = sidoList }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                if (e.InnerException == null) return Json(new { result = "FAILURE", msg = e.Message }, JsonRequestBehavior.AllowGet);
                else return Json(new { result = "FAILURE", msg = e.InnerException.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult GetAddressSigungu(string sido)
        {
            try
            {
                IList<AddressDto> sigunguList = nhibernateSession.CreateSQLQuery
                    ("select sido, sigungu from Address where sido = :sido")
                    .SetString("sido", sido)
                    .SetResultTransformer(new AliasToBeanResultTransformer(typeof(AddressDto)))
                    .List<AddressDto>();

                return Json(new { result = "SUCCESS", data = sigunguList }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                if (e.InnerException == null) return Json(new { result = "FAILURE", msg = e.Message }, JsonRequestBehavior.AllowGet);
                else return Json(new { result = "FAILURE", msg = e.InnerException.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult GetMarketBySigungu(string sigungu)
        {
            try
            {
                Address address = nhibernateSession.QueryOver<Address>()
                    .Where(x => x.Sigungu == sigungu)
                    .List()
                    .FirstOrDefault();
                IList<Market> marketList = nhibernateSession.QueryOver<Market>()
                    .Where(x => x.Address == address)
                    .List();

                return Json(new { result = "SUCCESS", data = marketList }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                if (e.InnerException == null) return Json(new { result = "FAILURE", msg = e.Message }, JsonRequestBehavior.AllowGet);
                else return Json(new { result = "FAILURE", msg = e.InnerException.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult SearchMarket(string searchText)
        {
            try
            {
                string sql = "select Id, Name from Market where name like :searchText or Address_id in ";
                sql += "(select id from Address where sido like :searchText or sigungu like :searchText)";

                IList<MarketDto> marketList = nhibernateSession.CreateSQLQuery(sql)
                    .SetString("searchText", "%"+searchText+"%")
                    .SetResultTransformer(new AliasToBeanResultTransformer(typeof(MarketDto)))
                    .List<MarketDto>();

                return Json(new { result = "SUCCESS", data = marketList }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                if (e.InnerException == null) return Json(new { result = "FAILURE", msg = e.Message }, JsonRequestBehavior.AllowGet);
                else return Json(new { result = "FAILURE", msg = e.InnerException.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult GetStoreMasterList(int? storeId)
        {
            try
            {
                if (storeId == null) return Json(new { result = "FAILURE", msg = "storeId가 입력되어야 합니다." }, JsonRequestBehavior.AllowGet);
                Store store = nhibernateSession.Get<Store>(storeId);
                if (store == null) return Json(new { result = "FAILURE", msg = "id가 " + storeId + "인 상점이 없습니다." }, JsonRequestBehavior.AllowGet);
                
                IList<Usersstore> usersStoreList = nhibernateSession.QueryOver<Usersstore>()
                    .Where(x=>x.Store == store)
                    .List();

                IList<Users> usersList = new List<Users>();
                foreach (Usersstore usersStore in usersStoreList)
                {
                    usersList.Add(usersStore.Users);
                }                   

                return Json(new { result = "SUCCESS", data = usersList }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                if (e.InnerException == null) return Json(new { result = "FAILURE", msg = e.Message }, JsonRequestBehavior.AllowGet);
                else return Json(new { result = "FAILURE", msg = e.InnerException.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult GetMyStoreList(string token)
        {
            try
            {
                if (token == null) return Json(new { result = "FAILURE", msg = "token이 입력되어야 합니다." }, JsonRequestBehavior.AllowGet);

                Users user = nhibernateSession.QueryOver<Users>()
                    .Where(x => x.Token == token)
                    .List()
                    .FirstOrDefault();
                if (user == null) return Json(new { result = "FAILURE", msg = "token이 " + token + "인 사용자가 없습니다." }, JsonRequestBehavior.AllowGet);
                                
                IList<Usersstore> usersStoreList = nhibernateSession.QueryOver<Usersstore>()
                    .Where(x => x.Users == user)
                    .List();

                IList<Store> storeList = new List<Store>();
                foreach (Usersstore usersStore in usersStoreList)
                {
                    storeList.Add(usersStore.Store);
                }

                return Json(new { result = "SUCCESS", data = storeList }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                if (e.InnerException == null) return Json(new { result = "FAILURE", msg = e.Message }, JsonRequestBehavior.AllowGet);
                else return Json(new { result = "FAILURE", msg = e.InnerException.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult GetMarket(int marketId)
        {
            try
            {
                Market market = nhibernateSession.Get<Market>(marketId);                
                return Json(new { result = "SUCCESS", data = market }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                if (e.InnerException == null) return Json(new { result = "FAILURE", msg = e.Message }, JsonRequestBehavior.AllowGet);
                else return Json(new { result = "FAILURE", msg = e.InnerException.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult GetStore(int storeId)
        {
            try
            {
                Store store = nhibernateSession.Get<Store>(storeId);
                return Json(new { result = "SUCCESS", data = store }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                if (e.InnerException == null) return Json(new { result = "FAILURE", msg = e.Message }, JsonRequestBehavior.AllowGet);
                else return Json(new { result = "FAILURE", msg = e.InnerException.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        
    }
}
